Appearance
[中文版本](/posts/c教程/zh-CN/07-贴近系统/068-Environment Variables)
Every program in Unix inherits a set of key–value pairs called environment variables. They store information about your shell, system configuration, and runtime behavior, such as your username, home directory, and compiler paths.
C gives you full control to read, modify, and define these variables directly.
Step 1. What Are Environment Variables?
Environment variables are strings of the form:
KEY=VALUEYou can view them in your shell:
printenvCommon examples:
HOME=/home/user
PATH=/usr/local/bin:/usr/bin:/bin
USER=alice
LANG=en_US.UTF-8
SHELL=/bin/bashThese values are passed to every program when you run it.
Step 2. Accessing Environment Variables in C
You can use the standard library functiongetenv() to read a variable.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
const char *path = getenv("PATH");
if (path)
printf("PATH = %s\n", path);
else
printf("PATH not found.\n");
}Output example:
PATH = /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbinIf the variable doesn’t exist,getenv() returnsNULL.
Step 3. Setting Environment Variables
To define or change a variable inside your program, usesetenv().
#include <stdlib.h>
#include <stdio.h>
int main(void) {
setenv("GREETING", "Hello from C!", 1);
printf("%s\n", getenv("GREETING"));
}setenv(name, value, overwrite)
overwrite = 0: don’t overwrite existing variable.overwrite = 1: replace it if it exists.
Output:
Hello from C!Step 4. Removing Environment Variables
Useunsetenv() to delete a variable.
#include <stdlib.h>
#include <stdio.h>
int main(void) {
setenv("TEMPVAR", "temporary", 1);
printf("Before unset: %s\n", getenv("TEMPVAR"));
unsetenv("TEMPVAR");
printf("After unset: %s\n", getenv("TEMPVAR"));
}Output:
Before unset: temporary
After unset: (null)Step 5. Accessing All Environment Variables
Theenviron global variable gives you access to the entire environment list.
#include <stdio.h>
extern char **environ;
int main(void) {
for (char **env = environ; *env != NULL; env++) {
printf("%s\n", *env);
}
}This prints all environment variables currently active in your process.
Step 6. Passing Environment Variables to Child Processes
When you usefork() andexec(), environment variables are inherited by the child process automatically.
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main(void) {
setenv("HELLO", "world", 1);
execlp("printenv", "printenv", "HELLO", NULL);
perror("execlp");
}Output:
worldYou can also provide a custom environment list usingexecle() orexecve().
Step 7. Custom Environment for a New Program
#include <unistd.h>
#include <stdio.h>
int main(void) {
char *newenv[] = { "MODE=debug", "VERSION=1.0", NULL };
execle("/usr/bin/env", "env", NULL, newenv);
perror("execle");
}Output:
MODE=debug
VERSION=1.0Only these two variables exist for the new process, everything else is discarded.
Step 8. Why Environment Variables Matter
They are a key part of Unix’s design philosophy:
- Programs should be configurable without recompilation.
- Environment variables provide global, process-level configuration.
For example:
PATHcontrols where executables are searched.HOMEdefines user directories.LANGdefines locale settings.LD_LIBRARY_PATHcontrols dynamic linking.
Step 9. Security Considerations
Environment variables are inherited automatically, so they can be a security risk if not handled carefully:
- Avoid trusting environment variables for authentication.
- Always validate
PATH,HOME, andTMPDIR. - Use
unsetenv()for sensitive contexts (e.g., setuid programs).
Tiny Code: Mini Shell with PATH Lookup
#include <stdio.h>
#include <stdlib.h>
int main(void) {
const char *path = getenv("PATH");
if (!path) path = "(none)";
printf("Current PATH:\n%s\n", path);
setenv("PATH", "/usr/local/bin:/usr/bin", 1);
printf("\nUpdated PATH:\n%s\n", getenv("PATH"));
}Output:
Current PATH:
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
Updated PATH:
/usr/local/bin:/usr/binStep 10. Why It Matters
Environment variables give your programs context:
- They tell you where files, libraries, and configs live.
- They let you control runtime behavior dynamically.
- They’re essential for system tools, shells, daemons, and tests.
Understanding how to read and modify them is key to mastering Unix programming in C.
Try It Yourself
- Print all environment variables sorted alphabetically.
- Implement your own
envcommand in C. - Write a program that modifies
PATHand launches another program. - Create a child process that inherits modified variables.
- Combine
setenv(),execle(), andgetenv()to simulate sandboxed runs.
Next, you’ll learn about error handling and return codes, the invisible signals that every Unix process uses to tell the system whether it succeeded or failed.
